<template>
  <div class="award-management-container">
    <!-- 搜索区域：仅管理员和审核员可见 -->
    <el-card v-if="!isTeacher" class="search-card">
      <div class="search-header">
        <h2>获奖管理</h2>
        <el-button type="primary" @click="handleAddAward">添加获奖</el-button>
      </div>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="教师姓名">
          <el-input v-model="searchForm.teacherName" placeholder="请输入教师姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="获奖名称">
          <el-input v-model="searchForm.name" placeholder="请输入获奖名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="奖项等级">
          <el-select v-model="searchForm.level" placeholder="请选择奖项等级" clearable style="width: 120px;">
            <el-option v-for="item in awardLevelOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颁发单位">
          <el-input v-model="searchForm.issuingUnit" placeholder="请输入颁发单位" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 教师视图：简化的头部 -->
    <el-card v-if="isTeacher" class="search-card">
      <div class="search-header">
        <h2>我的获奖</h2>
        <el-button type="primary" @click="handleAddAward">添加获奖</el-button>
      </div>
    </el-card>

    <!-- 获奖列表 -->
    <el-card class="list-card">
      <el-table 
        :data="awardList" 
        style="width: 100%" 
        v-loading="loading" 
        border
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="teacherName" label="教师姓名" min-width="100" v-if="!isTeacher"></el-table-column>
        <el-table-column prop="name" label="获奖名称" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="level" label="奖项等级" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getAwardLevelTag(scope.row.level)">{{ getAwardLevelText(scope.row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="issuingUnit" label="颁发单位" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="awardDate" label="获奖日期" width="120" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleEditAward(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteAward(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑获奖对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '添加获奖' : '编辑获奖'" 
      v-model="dialogVisible" 
      width="600px"
    >
      <el-form 
        :model="awardForm" 
        :rules="awardFormRules" 
        ref="awardFormRef" 
        label-width="100px"
      >
        <el-form-item label="教师" prop="teacherId" v-if="!isTeacher">
          <el-select v-model="awardForm.teacherId" placeholder="请选择教师" filterable style="width: 100%">
            <el-option 
              v-for="teacher in teacherOptions" 
              :key="teacher.id" 
              :label="teacher.realName + ' (' + teacher.department + ')'" 
              :value="teacher.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="获奖名称" prop="name">
          <el-input v-model="awardForm.name" placeholder="请输入获奖名称"></el-input>
        </el-form-item>
        <el-form-item label="奖项等级" prop="level">
          <el-select v-model="awardForm.level" placeholder="请选择奖项等级" style="width: 100%">
            <el-option v-for="item in awardLevelOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颁发单位" prop="issuingUnit">
          <el-input v-model="awardForm.issuingUnit" placeholder="请输入颁发单位"></el-input>
        </el-form-item>
        <el-form-item label="获奖日期" prop="awardDate">
          <el-date-picker v-model="awardForm.awardDate" type="date" placeholder="选择获奖日期" style="width: 100%" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select 
            v-model="awardForm.status" 
            placeholder="请选择状态" 
            style="width: 100%"
            :disabled="isTeacher">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <div v-if="isTeacher" class="status-note">
            <small>注：教师提交的获奖默认为待审核状态</small>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAwardForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../stores/user'

// 获取用户信息
const userStore = useUserStore()
const userRole = computed(() => userStore.userRole || localStorage.getItem('userRole'))
const isTeacher = computed(() => userRole.value === 'teacher')
const currentTeacherId = ref(null)

// 奖项等级选项
// 修改奖项等级选项
const awardLevelOptions = [
  { value: 'national', label: '国家级' },
  { value: 'provincial', label: '省级' }
]

// 获取奖项等级标签
const getAwardLevelTag = (level) => {
  const levelMap = {
    'national': 'danger',
    'provincial': 'warning'
  }
  return levelMap[level] || 'info'
}

// 获取奖项等级文本
const getAwardLevelText = (level) => {
  const levelMap = {
    'national': '国家级',
    'provincial': '省级'
  }
  return levelMap[level] || level
}
const statusOptions = [
  { value: 'pending', label: '待审核' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '已拒绝' }
]



// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 搜索表单
const searchForm = reactive({
  teacherName: '',
  name: '',
  level: '',
  issuingUnit: '',
  status: ''
})

// 获奖列表数据
const awardList = ref([])
const loading = ref(false)

// 教师选项
const teacherOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const awardFormRef = ref(null)
const submitLoading = ref(false)

// 获奖表单
const awardForm = reactive({
  id: null,
  teacherId: '',
  name: '',
  level: '',
  issuingUnit: '',
  awardDate: '',
  status: 'pending'
})

// 获奖表单验证规则
const awardFormRules = {
  teacherId: [
    { required: true, message: '请选择教师', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入获奖名称', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择奖项等级', trigger: 'change' }
  ],
  issuingUnit: [
    { required: true, message: '请输入颁发单位', trigger: 'blur' }
  ],
  awardDate: [
    { required: true, message: '请选择获奖日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取当前教师ID
const fetchCurrentTeacherId = async () => {
  if (isTeacher.value) {
    try {
      // 修正：从localStorage获取user并解析JSON
      let userId = userStore.userId
      if (!userId) {
        const userStr = localStorage.getItem('user')
        if (userStr) {
          try {
            const userObj = JSON.parse(userStr)
            userId = userObj.id
          } catch (e) {
            console.error('解析用户信息错误:', e)
          }
        }
      }
      
      if (userId) {
        const response = await axios.get(`http://localhost:8081/api/teacher/getByUserId?userId=${userId}`)
        if (response.data.code === 200 && response.data.data) {
          // 从返回的数据中获取教师ID
          currentTeacherId.value = response.data.data.teacher.id
        }
      } else {
        console.error('未找到用户ID')
      }
    } catch (error) {
      console.error('获取当前教师ID错误:', error)
    }
  }
}

// 获取获奖列表
const fetchAwardList = async () => {
  loading.value = true
  try {
    const params = {}
    
    // 如果是教师角色，只查询自己的获奖
    if (isTeacher.value && currentTeacherId.value) {
      params.teacherId = currentTeacherId.value
    } else {
      // 管理员或审核员可以按条件筛选
      params.teacherName = searchForm.teacherName
      params.name = searchForm.name
      params.level = searchForm.level
      params.issuingUnit = searchForm.issuingUnit
      params.status = searchForm.status
    }
    
    const response = await axios.post('http://localhost:8081/api/award/list', params)
    if (response.data.code === 200) {
      // 处理返回的数据结构
      if (response.data.data && Array.isArray(response.data.data)) {
        // 如果是教师角色，手动筛选数据
        if (isTeacher.value && currentTeacherId.value) {
          awardList.value = response.data.data.filter(item => 
            item.award && item.award.teacherId === currentTeacherId.value
          ).map(item => ({
            id: item.award.id,
            teacherId: item.award.teacherId,
            teacherName: item.teacherName,
            departmentName: item.departmentName,
            name: item.award.name,
            level: item.award.level,
            issuingUnit: item.award.issuingUnit,
            awardDate: item.award.awardDate,
            status: item.award.status
          }));
        } else {
          awardList.value = response.data.data.map(item => ({
            id: item.award.id,
            teacherId: item.award.teacherId,
            teacherName: item.teacherName,
            departmentName: item.departmentName,
            name: item.award.name,
            level: item.award.level,
            issuingUnit: item.award.issuingUnit,
            awardDate: item.award.awardDate,
            status: item.award.status
          }));
        }
      } else {
        awardList.value = [];
      }
    } else {
      ElMessage.error(response.data.msg || '获取获奖列表失败')
    }
  } catch (error) {
    console.error('获取获奖列表错误:', error)
    ElMessage.error('获取获奖列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 获取教师列表（用于下拉选择）
const fetchTeacherOptions = async () => {
  // 如果是教师角色，不需要获取教师列表
  if (isTeacher.value) return
  
  try {
    const response = await axios.post('http://localhost:8081/api/teacher/list', {})
    if (response.data.code === 200) {
      teacherOptions.value = response.data.data.map(item => ({
        id: item.teacher.id,
        realName: item.user.realName,
        department: item.teacher.department
      }))
    } else {
      ElMessage.error(response.data.msg || '获取教师列表失败')
    }
  } catch (error) {
    console.error('获取教师列表错误:', error)
    ElMessage.error('获取教师列表失败，请检查网络连接')
  }
}

// 搜索获奖
const handleSearch = () => {
  fetchAwardList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchAwardList()
}

// 添加获奖
const handleAddAward = () => {
  dialogType.value = 'add'
  resetAwardForm()
  
  // 如果是教师角色，自动设置教师ID
  if (isTeacher.value && currentTeacherId.value) {
    awardForm.teacherId = currentTeacherId.value
  }
  
  dialogVisible.value = true
}

// 编辑获奖
const handleEditAward = (row) => {
  dialogType.value = 'edit'
  awardForm.id = row.id
  awardForm.teacherId = row.teacherId
  awardForm.name = row.name
  awardForm.level = row.level
  awardForm.issuingUnit = row.issuingUnit
  awardForm.awardDate = row.awardDate
  awardForm.status = row.status
  
  dialogVisible.value = true
}

// 重置获奖表单
const resetAwardForm = () => {
  if (awardFormRef.value) {
    awardFormRef.value.resetFields()
  }
  
  awardForm.id = null
  awardForm.teacherId = ''
  awardForm.name = ''
  awardForm.level = ''
  awardForm.issuingUnit = ''
  awardForm.awardDate = ''
  awardForm.status = 'pending'
}

// 提交获奖表单
const submitAwardForm = () => {
  // 如果是教师角色，确保使用当前教师ID和待审核状态
  if (isTeacher.value && currentTeacherId.value) {
    awardForm.teacherId = currentTeacherId.value
    awardForm.status = 'pending' // 教师提交的获奖始终为待审核状态
  }
  
  awardFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8081/api/award/add' 
          : 'http://localhost:8081/api/award/update'
        
        const response = await axios.post(url, {
          id: awardForm.id,
          teacherId: awardForm.teacherId,
          name: awardForm.name,
          level: awardForm.level,
          issuingUnit: awardForm.issuingUnit,
          awardDate: awardForm.awardDate,
          status: awardForm.status
        })
        
        if (response.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加获奖成功' : '编辑获奖成功')
          dialogVisible.value = false
          fetchAwardList() // 刷新列表
        } else {
          ElMessage.error(response.data.msg || (dialogType.value === 'add' ? '添加获奖失败' : '编辑获奖失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加获奖错误:' : '编辑获奖错误:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加获奖失败，请检查网络连接' : '编辑获奖失败，请检查网络连接')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除获奖
const handleDeleteAward = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除获奖 "${row.name}" 吗？此操作将不可逆！`,
      '删除获奖',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const params = new URLSearchParams()
    params.append('id', row.id)
    
    const response = await axios.post('http://localhost:8081/api/award/delete', params)
    
    if (response.data.code === 200) {
      ElMessage.success('删除获奖成功')
      fetchAwardList() // 刷新列表
    } else {
      ElMessage.error(response.data.msg || '删除获奖失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除获奖错误:', error)
      ElMessage.error('删除获奖失败，请检查网络连接')
    }
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchCurrentTeacherId()
  fetchAwardList()
  fetchTeacherOptions()
})
</script>

<style scoped>
.award-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-top: 15px;
}

.list-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}
</style>